import cv2
import numpy as np
import matplotlib.pyplot as plt


def calcGrayHist(I):
    # 计算灰度直方图
    h, w = I.shape[:2]
    grayHist = np.zeros([256], np.uint64)
    for i in range(h):
        for j in range(w):
            grayHist[I[i][j]] += 1
    return grayHist


def showGrayHist(image, title):
    grayHist = calcGrayHist(image)
    x = np.arange(256)
    # 绘制灰度直方图
    plt.plot(x, grayHist, 'r', linewidth=2, c='black')
    plt.xlabel("gray Label")
    plt.ylabel(title)
    plt.show()


def imageEnhance(img):
    # print("对单张票据进行图像增强")
    cv2.imshow("enhance_origin", img)
    img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    # 限制对比度的自适应阈值均衡化
    clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
    dst = clahe.apply(img)
    cv2.imshow("enhance_dst", dst)
    return dst

    # # 直方图正规化
    # Imin, Imax = cv.minMaxLoc(img)[:2]
    # Omin, Omax = 0, 255
    # a = float(Omax - Omin) / (Imax - Imin)
    # b = Omin - a * Imin
    # normalize_img = a * img + b
    # normalize_img = normalize_img.astype(np.uint8)
    # showGrayHist(normalize_img, "normalize_img")
    # cv.imshow("normalize_img", normalize_img)
    #
    # # 伽马变换
    # fi = img / 255.0
    # gamma = 2.0
    # gamma_img = np.power(fi, gamma)
    # # showGrayHist(gamma_img, "gamma_img")
    # cv.imshow("gamma_img", gamma_img)
    #
    # # 全局直方图均衡化
    # h, w = img.shape
    # # 第一步：计算灰度直方图
    # grayHist = calcGrayHist(img)
    # # 第二步：计算累加灰度直方图
    # zeroCumuMoment = np.zeros([256], np.uint32)
    # for p in range(256):
    #     if p == 0:
    #         zeroCumuMoment[p] = grayHist[0]
    #     else:
    #         zeroCumuMoment[p] = zeroCumuMoment[p - 1] + grayHist[p]
    # # 第三步：根据累加灰度直方图得到输入灰度级和输出灰度级之间的映射关系
    # outPut_q = np.zeros([256], np.uint8)
    # cofficient = 256.0 / (h * w)
    # for p in range(256):
    #     q = cofficient * float(zeroCumuMoment[p]) - 1
    #     if q >= 0:
    #         outPut_q[p] = math.floor(q)
    #     else:
    #         outPut_q[p] = 0
    # # 第四步：得到直方图均衡化后的图像
    # equalHistImage = np.zeros(img.shape, np.uint8)
    # for i in range(h):
    #     for j in range(w):
    #         equalHistImage[i][j] = outPut_q[img[i][j]]
    # cv.imshow("equalHistImage", equalHistImage)


